from utils.bbox_utils import xywh2xyxy


def _get_inter_area(box1, box2):
    x1, y1, x2, y2 = xywh2xyxy(*box1)
    x3, y3, x4, y4 = xywh2xyxy(*box2)
    if x1 >= x4 or x2 <= x3:
        return 0
    if y1 >= y4 or y2 <= y3:
        return 0
    x_list = sorted([x1, x2, x3, x4])
    inter_area_width = x_list[2] - x_list[1]

    y_list = sorted([y1, y2, y3, y4])
    inter_area_height = y_list[2] - y_list[1]

    return inter_area_width * inter_area_height


def get_IoU(box1, box2):
    """
    计算两个框的IoU
    """
    box1_area = box1[2] * box1[3]
    box2_area = box2[2] * box2[3]
    inter_area = _get_inter_area(box1, box2)
    union_area = box1_area + box2_area - inter_area
    return inter_area / union_area
